from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.api.datastore_errors import BadKeyError
from app.helpers.access import requires_admin
from app.helpers.views import renders_template
from app.models.permissions import UserPermission, \
  PERMISSIONS, add_permissions_for
import urllib


class AccessLogout(webapp.RequestHandler):
  """ Sign out page """
  def get(self):
    msg = urllib.urlencode({'flash' : 'You have been logged out'})
    self.redirect(users.create_logout_url("/?" + msg))


class AccessLogin(webapp.RequestHandler):
  """ Sign in page """
  def get(self):
    self.redirect(users.create_login_url("/"))


class AccessNopermission(webapp.RequestHandler):
  """ Page to show when user has no access rights
  """
  def get(self):
    msg = urllib.urlencode({'flash' : "You don't have permission to do that"})
    self.redirect(users.create_logout_url("/?" + msg))


class AccessPermissions(webapp.RequestHandler):
  """ Manage permissions """
  @requires_admin
  @renders_template('access', 'manage.html')
  def get(self):
    return {
      'permissions' : PERMISSIONS.items(),
      'user_permissions' : UserPermission.all().fetch(1000)
    }


class AccessPermissionsAdd(webapp.RequestHandler):
  """ Manage permissions """
  @requires_admin
  def post(self):
    email = self.request.get('email')
    if not email:
      flash = "Email required for new user!"
      
    else:  
      permissions = []
      for key,value in self.request.params.items():
        if key == 'new_user':
          permissions.append(value)
      
      add_permissions_for(email, *permissions)
      flash = "New user (%s) added" % email
    
    self.redirect('/access/permissions?' + urllib.urlencode({'flash' : flash}))
    

class AccessPermissionsUpdate(webapp.RequestHandler):
  """ Manage permissions """
  @requires_admin
  def post(self):
    fetched = {}
    def _get_user(key):
      u = UserPermission.get(key)
      u._old_values = u.permissions
      u.permissions = []
      return u
    
    try:
      for key,value in self.request.params.items():
        user = fetched.setdefault(key, _get_user(key))
        user.permissions.append(value)
      
      count = 0
      for up in fetched.values():
        if up.permissions != up._old_values:
          count += 1
          up.put()
      
      flash = "Permissions updated for %s users" % count
        
    except BadKeyError:
      flash = "Error: Trying to update non-existent user!"
    
    self.redirect('/access/permissions?' + urllib.urlencode({'flash' : flash}))
